package com.dummies.android.taskreminder;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;

public class OnBootReceiver extends BroadcastReceiver {

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.d("==OnBootReceiver==", "==onReceive==");
		ReminderManager reminderMgr = new ReminderManager(context);
		RemindersDbAdapter dbHelper = new RemindersDbAdapter(context);
		dbHelper.open();
		Cursor cursor = dbHelper.fetchAllReminders();
		if (cursor != null) {
			cursor.moveToFirst();
			int rowIdColumnIndex = cursor
					.getColumnIndex(RemindersDbAdapter.KEY_ROWID);
			int dateTimeColumnIndex = cursor
					.getColumnIndex(RemindersDbAdapter.KEY_DATE_TIME);
			int titleColumnIndex = cursor.getColumnIndex(RemindersDbAdapter.KEY_TITLE);
			int bodyColumnIndex = cursor.getColumnIndex(RemindersDbAdapter.KEY_BODY);
			while (cursor.isAfterLast() == false) {
				Long rowId = cursor.getLong(rowIdColumnIndex);
				String dateTime = cursor.getString(dateTimeColumnIndex);
				String title = cursor.getString(titleColumnIndex);
				String body = cursor.getString(bodyColumnIndex);
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat format = new SimpleDateFormat(
						ReminderEditActivity.DATE_TIME_FORMAT);
				try {
					java.util.Date date = format.parse(dateTime);
					cal.setTime(date);
					reminderMgr.setReminder(rowId, cal, title, body);
				} catch (Exception e) {
					Log.e("OnBootReceiver", e.getMessage(), e);
				}
				cursor.moveToNext();
			}
			cursor.close();
		}
		dbHelper.close();
	}

}
